///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.browser {
	import com.adobe.serialization.json.JSON;
	
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.utils.getQualifiedClassName;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import sugarcookie.data.vo.Anchor;
	import sugarcookie.error.ApplicationError;
	
	/**
	 * Executes an external, download or popup link.
	 */
	public class Link {
		private static var _log:ILogger;
		private static var _file:FileReference;
		
		/**
		 * Executes a URI based on link object received.  Link object can be either a basic object (usually from JSON based data) or an Anchor vo object.
		 * 
		 * @param link When using a generic object, follow this object schema: {uri:"/link-to-resource", type:"external}download|popup", target:"_top|_self|_blank|_parent", props:"only used when type is popup.  props are same as window.open specs arg"}
		 * 
		 * @see sugarcookie.commands.LinkCommand
		 */
		public static function execute(link:*):void {
			var objType:String = getQualifiedClassName(link);
			if (objType.indexOf("Anchor")!=-1) processAnchor(link);
			else executeLink(link);
		}
		
		private static function processAnchor(anchor:Anchor):void {
			var link:Object = {};
			link.uri = anchor.href;
			link.type = anchor.type;
			link.name = anchor.name;
			if (anchor.href.indexOf("?")!=-1) {
				var propStr:String = anchor.href.substring(anchor.href.indexOf("?")+1);
				link.props = JSON.decode(propStr);
			}
			
			executeLink(link);
		}
		
		private static function executeLink(link:Object):void {
			if (link==null) throw new ApplicationError("The link object has not been assigned.");
			if (_log==null) _log = Log.getLogger("sugarcookie.browser.Link");
			switch (link.type) {
				case "external":
					try {            
						navigateToURL(new URLRequest(link.uri),link.target);
					} catch (e:Error) {
						_log.error("Unable to navigate to requested url: "+link.uri);
					}
					break;
				case "download":
					var request:URLRequest = new URLRequest();
					request.url = link.uri;
					_file = new FileReference();
					_file.download(request);
					break;
				case "popup":
					Popup.closeAllPopups();
					Popup.createPopupWindow(link.uri,link.name,link.props);
					break;
			}
		}
	}
}